package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserManagementDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;

import com.itheima.pojo.User;
import com.itheima.utils.DateUtils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**

 * 用户服务
 */

@Service(interfaceClass = UserManagementService.class)
@Transactional
public class UserManagementServiceImpl implements UserManagementService {
    @Resource
    private UserManagementDao userManagementDao;

    //1.1新增角色，同时需要添加角色关联的权限表
    public void add(Map map, Integer[] roleIds) {

        //新增角色，操作t_role表
        //1.处理用户的密码，将密码加密成密文形式，用于SpringSecurity安全验证登录
        String password = (String) map.get("password");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);

        //2.处理用户的出生日期
        String birthday = (String) map.get("birthday");
        User user = new User();
        try {
            user.setBirthday(DateUtils.parseString2Date(birthday));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setPassword(encode);
        user.setUsername((String) map.get("username"));
        user.setGender((String) map.get("gender"));
        user.setRemark((String) map.get("remark"));
        user.setStation((String) map.get("station"));
        user.setTelephone((String) map.get("telephone"));

        userManagementDao.add(user);
        //设置用户和角色的多对多的关联关系，操作t_user_role表
        Integer userId = user.getId();
        this.setUserAndRole(userId, roleIds);

    }
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String, Object>> page = userManagementDao.findByCondition(queryPageBean);
        List<Map<String, Object>> list = page.getResult();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {

                //处理日期格式
                Date birthday = (Date) map.get("birthday");
                try {
                    map.put("birthday", DateUtils.parseDate2String(birthday));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    public User findById(Integer id) {
        return userManagementDao.findById(id);
    }


    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userManagementDao.findRoleIdsByUserId(id);
    }


    public void edit(Map map, Integer[] roleIds) {
//1.处理用户的密码，将密码加密成密文形式，用于SpringSecurity安全验证登录
        String password = (String) map.get("password");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);

        //2.处理用户的出生日期
        String birthday = (String) map.get("birthday");
        User user = new User();
        try {
            user.setBirthday(DateUtils.parseString2Date(birthday));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setPassword(encode);
        user.setId( (Integer) map.get("id"));
        user.setUsername((String) map.get("username"));
        user.setGender((String) map.get("gender"));
        user.setRemark((String) map.get("remark"));
        user.setStation((String) map.get("station"));
        user.setTelephone((String) map.get("telephone"));

        userManagementDao.edit(user);
        //清理当前用户关联的角色，操作中间关系表t_user_role表
        userManagementDao.deleteAssocication(user.getId());
        //重新建立当前用户和角色的关联关系
        Integer userId = user.getId();
        this.setUserAndRole(userId, roleIds);
    }

    public void deleteAssocication(Integer id) {

        //清理当前角色关联的权限，操作中间关系表t_role_permission表
        userManagementDao.deleteAssocication(id);

        //最后根据 Integer id 删除角色表中对应的角色数据。
        userManagementDao.deleteById(id);
    }
    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userManagementDao.setUserAndRole(map);
            }
        }
    }

}
